﻿using System;
using System.Web.Mvc;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using TBM.Filters;
using TBM.Tools;

namespace TBM.Controllers
{
    [Authorize]
    [Description("用户管理")]
    public partial class UserController : MasterController
    {
        /// <summary>
        /// 添加用户到组
        /// </summary>
        /// <param name="gids"></param>
        /// <param name="uids"></param>
        /// <returns></returns>
        private JsonResult _UserToGroup(string[] gids, string[] uids)
        {
            JsonResult result = new JsonResult();

            cmd.CommandText = "p_AppendToGroup";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@Groups", SqlDbType.VarChar, 500);
            cmd.Parameters.Add("@UIDs", SqlDbType.VarChar, 1000);
            cmd.Parameters["@Groups"].Value = String.Join(",", gids);
            cmd.Parameters["@UIDs"].Value = String.Join(",", uids);

            Core.LangItem li = cmd.ExecuteNonQuery() > 0 ? Core.Lang.APPEND_TO_GROUPS_SUCCESS : Core.Lang.APPEND_TO_GROUPS_FAILED;
            result.Data = new Models.ExecuteResult
            {
                Result = li.Code == Core.Lang.APPEND_TO_GROUPS_SUCCESS.Code,
                Code = li.Code,
                Message = li.Message
            };

            return result;
        }

        /// <summary>
        /// 更新模块权限
        /// </summary>
        /// <param name="objid">UID或GID</param>
        /// <returns></returns>
        private JsonResult _UpdatePermission(string objid)
        {
            JsonResult result = new JsonResult();

            cmd.CommandText = "p_UpdateModulePermissions";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Clear();

            cmd.Parameters.Add("@OBJID", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@ModuleIDs", SqlDbType.VarChar, 8000);
            cmd.Parameters.Add("@Return", SqlDbType.Int);
            cmd.Parameters["@OBJID"].Value = objid;
            cmd.Parameters["@ModuleIDs"].Value = Core.CommandParamType.NullOrString(Request["moduleid"]);
            cmd.Parameters["@Return"].Direction = ParameterDirection.ReturnValue;

            cmd.ExecuteNonQuery();

            Core.LangItem li = (int)cmd.Parameters["@Return"].Value == 0 ? Core.Lang.CMD_SUCCESS : Core.Lang.PERMISSION_UPDATE_FAILED;

            result.Data = new Models.ExecuteResult
            {
                Result = li.Code == Core.Lang.CMD_SUCCESS.Code,
                Code = li.Code,
                Message = li.Message
            };

            return result;
        }


        /// <summary>
        /// 更新菜单权限
        /// </summary>
        /// <param name="objid">UID或GID</param>
        /// <returns></returns>
        private JsonResult _UpdateMenuPermission(string objid)
        {
            JsonResult result = new JsonResult();

            cmd.CommandText = "p_UpdateMenuPermissions";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Clear();

            cmd.Parameters.Add("@OBJID", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@PIDs", SqlDbType.VarChar, 8000);
            cmd.Parameters.Add("@Return", SqlDbType.Int);
            cmd.Parameters["@OBJID"].Value = objid;
            cmd.Parameters["@PIDs"].Value = Core.CommandParamType.NullOrString(Request["id"]);
            cmd.Parameters["@Return"].Direction = ParameterDirection.ReturnValue;

            cmd.ExecuteNonQuery();

            Core.LangItem li = (int)cmd.Parameters["@Return"].Value == 0 ? Core.Lang.CMD_SUCCESS : Core.Lang.PERMISSION_UPDATE_FAILED;

            result.Data = new Models.ExecuteResult
            {
                Result = li.Code == Core.Lang.CMD_SUCCESS.Code,
                Code = li.Code,
                Message = li.Message
            };

            return result;
        }


        /// <summary>
        /// 更新用户头像
        /// </summary>
        /// <param name="uid">UID</param>
        /// <returns></returns>
        private JsonResult _UpdateAvatar(string uid)
        {
            var avatarFile = Request.Files["avatar"];
            string avatarPath = "";
            string avatarStorePath = "";
            if (avatarFile != null)
            {
                avatarStorePath = Core.Config.FileDirectory + "avatar/" + uid + "/";
                // 头像存储位置
                avatarPath = Server.MapPath(avatarStorePath);

                avatarStorePath = avatarStorePath.TrimStart(new char[] { '~' });

                if (!Directory.Exists(avatarPath)) Directory.CreateDirectory(avatarPath);
            }

            ImageScaling isc = new ImageScaling(avatarFile.InputStream);

            isc.ScaleToSave(avatarPath + "large.png", 125, 125, System.Drawing.Imaging.ImageFormat.Png);
            isc.ScaleToSave(avatarPath + "small.png", 30, 30, System.Drawing.Imaging.ImageFormat.Png);

            avatarFile.InputStream.Close();

            cmd.CommandText = "update dbo.Users set PicUrl = @PicUrl where UID = @UID";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@UID", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@PicUrl", SqlDbType.VarChar, 50);
            cmd.Parameters["@UID"].Value = uid;
            cmd.Parameters["@PicUrl"].Value = avatarStorePath;

            Core.LangItem li = cmd.ExecuteNonQuery() > 0 ? Core.Lang.UPDATE_AVATAR_SUCCESS : Core.Lang.UPDATE_AVATAR_FAILED;
            JsonResult result = new JsonResult();

            result.Data = new Models.ExecuteResult
            {
                Result = li.Code == Core.Lang.UPDATE_AVATAR_SUCCESS.Code,
                Code = li.Code,
                Message = li.Message,
                Data = new
                {
                    PicUrl = avatarStorePath,
                    UID = uid
                }
            };

            return result;
        }


        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="uid">用户UID</param>
        /// <param name="firstname">姓氏</param>
        /// <param name="lastname">名字</param>
        /// <param name="email">Email</param>
        /// <param name="updateGroup">是否更新分组</param>
        /// <returns></returns>
        private JsonResult _UpdateUser(string uid, string firstname, string lastname, string email, bool updateGroup)
        {
            JsonResult result = new JsonResult();

            cmd.CommandText = "p_UpdateUser";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Clear();

            cmd.Parameters.Add("@UID", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@Groups", SqlDbType.VarChar, 500);
            cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar, 15);
            cmd.Parameters.Add("@LastName", SqlDbType.NVarChar, 15);
            cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100);
            cmd.Parameters.Add("@Phone", SqlDbType.VarChar, 11);
            cmd.Parameters.Add("@QQ", SqlDbType.VarChar, 11);
            cmd.Parameters.Add("@CNName", SqlDbType.Bit);
            cmd.Parameters.Add("@Memo", SqlDbType.NVarChar, 200);
            cmd.Parameters.Add("@UpdateGroup", SqlDbType.Bit);
            cmd.Parameters.Add("@Return", SqlDbType.Int);

            object cnname = Core.CommandParamType.Boolean(Request["cnname"]);
            object phone = Core.CommandParamType.NullOrString(Request["phone"]);
            object qq = Core.CommandParamType.NullOrString(Request["qq"]);
            object memo = Core.CommandParamType.NullOrString(Request["memo"]);

            cmd.Parameters["@UID"].Value = uid;
            cmd.Parameters["@Groups"].Value = Core.CommandParamType.NullOrString(Request["groups"]);
            cmd.Parameters["@FirstName"].Value = firstname;
            cmd.Parameters["@LastName"].Value = lastname;
            cmd.Parameters["@Email"].Value = email;
            cmd.Parameters["@Phone"].Value = phone;
            cmd.Parameters["@QQ"].Value = qq;
            cmd.Parameters["@CNName"].Value = cnname;
            cmd.Parameters["@Memo"].Value = memo;
            cmd.Parameters["@UpdateGroup"].Value = updateGroup;
            cmd.Parameters["@Return"].Direction = ParameterDirection.ReturnValue;

            //cmd.ExecuteReader();

            object groups = cmd.ExecuteScalar();

            Core.LangItem li = (int)cmd.Parameters["@Return"].Value == 0 ? Core.Lang.CMD_SUCCESS : Core.Lang.CMD_EMAIL_EXISTS;

            result.Data = new Models.ExecuteResult
            {
                Result = li.Code == Core.Lang.CMD_SUCCESS.Code,
                Code = li.Code,
                Message = li.Message,
                Data = new
                {
                    UID = uid,
                    CNName = cnname,
                    Groups = groups,
                    FirstName = firstname,
                    LastName = lastname,
                    Email = email,
                    Phone = phone,
                    QQ = qq,
                    Memo = memo
                }
            };

            return result;
        }


        /// <summary>
        /// 获取对象的菜单列表
        /// </summary>
        /// <param name="objectid"></param>
        /// <returns></returns>
        private List<Models.MainMenu> GetObjectMenu(string objectid, int type)
        {
            List<Models.MainMenu> menu = new List<Models.MainMenu>();
            List<Models.MainMenu> pages = new List<Models.MainMenu>();
            cmd.CommandText = "p_PageInObject";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@OBJ_ID", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@Type", SqlDbType.Int);
            cmd.Parameters["@OBJ_ID"].Value = objectid;
            cmd.Parameters["@Type"].Value = type;

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    pages.Add(new Models.MainMenu
                    {
                        ID = (int)dr["ID"],
                        PID = (int)dr["PID"],
                        PageName = dr["PageName"].ToString(),
                        SubTitle = dr["SubTitle"].ToString(),
                        IsChecked = (bool)dr["IsChecked"]
                    });
                }
            }

            foreach (TBM.Models.MainMenu item in pages.Where(a => a.PID == 0))
            {
                menu.Add(item);
                AddSubMenu(item, pages);
            }

            return menu;
        }
        
        /// <summary>
        /// 添加子菜单
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="pageList"></param>
        private void AddSubMenu(Models.MainMenu parent, List<TBM.Models.MainMenu> pageList)
        {
            List<TBM.Models.MainMenu> subList = pageList.Where(a => a.PID == parent.ID).ToList();

            if (subList.Count == 0) return;

            foreach (TBM.Models.MainMenu item in subList)
            {
                AddSubMenu(item, pageList);
            }

            parent.SubMenu = subList;
        }


        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="uid">用户UID</param>
        /// <param name="newpassword">新的密码</param>
        /// <param name="currpassword">当前密码</param>
        /// <returns></returns>
        private JsonResult _UpdatePWD(string uid, string newpassword, string currpassword)
        {
            cmd.CommandText = "update dbo.Users set [Password] = @Password where UID = @UID and [Password] = @CurrPwd";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Clear();

            cmd.Parameters.Add("@UID", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@Password", SqlDbType.Char, 32);
            cmd.Parameters.Add("@CurrPwd", SqlDbType.Char, 32);

            cmd.Parameters["@UID"].Value = uid;
            cmd.Parameters["@CurrPwd"].Value = Core.App.GetPassword(currpassword);
            cmd.Parameters["@Password"].Value = Core.App.GetPassword(newpassword);

            Core.LangItem li = cmd.ExecuteNonQuery() > 0 ? Core.Lang.CMD_SUCCESS : Core.Lang.PREVIOUS_PASSWORD_ERROR;
            JsonResult result = new JsonResult();

            result.Data = new Models.ExecuteResult
            {
                Result = li.Code == Core.Lang.CMD_SUCCESS.Code,
                Code = li.Code,
                Message = li.Message
            };

            return result;
        }
    }
}
